package com.xgk.boot.module.core.ui;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class ErrorExceptionHandler extends DefaultErrorWebExceptionHandler {

    private final boolean goToIndex = true;
    public static final String DEFAULT_INDEX = "/index.html";

    public ErrorExceptionHandler(ErrorAttributes errorAttributes, WebProperties.Resources resources, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resources, errorProperties, applicationContext);
    }

    //    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        int code = 500;
        Throwable error = super.getError(request);
        if(error instanceof ResponseStatusException) {
            code = ((ResponseStatusException) error).getStatusCode().hashCode();
        }
        return response(code, this.buildMessage(request, error));
    }

    public static Map<String, Object> response(int status, String message) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", status);
        map.put("message", message);
        map.put("data", null);
        return map;
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     *
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        Map<String, Object> error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        Integer status = (Integer) error.get("status");
        String path = (String) error.get("path");
        String redirect = null;
        if(goToIndex && status == HttpStatus.NOT_FOUND.value()) {
            redirect = getIndex(path);
        }
        if(redirect != null) {
            return ServerResponse.temporaryRedirect(URI.create(redirect)).build();
        } else {
            return ServerResponse.status(getHttpStatus(error)).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(error));
        }

    }


    private String getIndex(String uri) {
            return DEFAULT_INDEX;

    }

    private String getParent(String uri) {
        StringBuilder index = new StringBuilder();
        int splitCount = 0;
        for(int i = 0; i < uri.length(); i++) {
            char c = uri.charAt(i);
            if(c == '/') {
                splitCount++;
            }
            index.append(c);
            if(splitCount >= 2) {
                break;
            }
        }
        index.append("index.html");
        return index.toString();
    }

    /**
     * 根据code获取对应的HttpStatus
     *
     * @param errorAttributes
     * @return
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        return (int) errorAttributes.get("status");
    }

    /**
     * 构建异常信息
     *
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if(ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
        }
        return message.toString();
    }
}
